﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace Communication
{
    /**
     * Класс обеспечивает прием и передачу данных по протоколу TCP
     */ 
    public class ClientCommunicator: ICommunicator
    {
    	public ClientCommunicator(IPEndPoint endpoint)
        {
        	this.endpoint = endpoint;
        }

    	public Byte[] DoCommunicate(Byte[] msg)
    	{
    		var client = new TcpClient();
			client.Connect(endpoint);

			using (NetworkStream stream = client.GetStream())
			{
				var tmp = BitConverter.GetBytes(msg.Length);
				stream.Write(tmp, 0, tmp.Length);
				stream.Write(msg, 0, msg.Length);

				var data = new Byte[256];
				var ms = new MemoryStream();
				int bytesRead;
				while ((bytesRead = stream.Read(data, 0, data.Length)) > 0)
					ms.Write(data, 0, bytesRead);

				var result = new byte[ms.Length];
				Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);

				return result;
			}
		}

    	private readonly IPEndPoint endpoint;
    }
}
